package com.hao.word;

import com.aspose.words.*;

import javax.swing.filechooser.FileSystemView;
import java.io.File;

public class CreateTable {
    private static FileSystemView fsv = FileSystemView.getFileSystemView();
    private static File com = fsv.getHomeDirectory();
    private static final String PATH = com + File.separator;

    public static void main(String[] args) throws Exception {

        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        Table table = builder.startTable();
        for (int i = 0; i < 100; i++) {
            builder.insertCell();
            builder.writeln("Cell #" + i + "a");
            builder.insertCell();
            builder.writeln("Cell #" + i + "b");
            builder.endRow();
        }

        Row firstRow = table.getFirstRow();

        firstRow.getRowFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        firstRow.getRowFormat().setHeightRule(HeightRule.AUTO);
        firstRow.getRowFormat().setAllowBreakAcrossPages(true);
        for (Cell cell : (Iterable<Cell>) firstRow.getChildNodes(NodeType.CELL, true)) {
            for (Paragraph paragraph : cell.getParagraphs()) {
                //System.out.println(paragraph.getText());
            }
        }
        builder.moveToParagraph(1, 0);
        LayoutCollector collector = new LayoutCollector(doc);

        int pageIndex = 1;
        for (Section section : doc.getSections()) {
            NodeCollection paragraphs = section.getBody().getChildNodes(NodeType.PARAGRAPH, true);
            for (Paragraph para : (Iterable<Paragraph>) paragraphs) {
                if (collector.getStartPageIndex(para) == pageIndex) {
                    builder.moveToParagraph(paragraphs.indexOf(para), 0);
                    builder.startBookmark("BM_Page" + pageIndex);
                    builder.endBookmark("BM_Page" + pageIndex);
                    pageIndex++;
                }
            }
        }

        for (Bookmark bookmark : doc.getRange().getBookmarks()) {
            if (bookmark.getName().startsWith("BM_")) {
                Paragraph para = (Paragraph) bookmark.getBookmarkStart().getParentNode();
                System.out.println(para.getText());
            }
        }
        System.out.println("end ...");
        doc.save(PATH + "TableOut.doc");
    }

    public static void InsertWatermarkImageAtEachPage(Document doc, String watermarkImagePath) throws Exception {
        DocumentBuilder builder = new DocumentBuilder(doc);

        LayoutCollector collector = new LayoutCollector(doc);

        int pageIndex = 1;
        for (Section section : doc.getSections()) {
            NodeCollection paragraphs = section.getBody().getChildNodes(NodeType.PARAGRAPH, true);
            for (Paragraph para : (Iterable<Paragraph>) paragraphs) {
                if (collector.getStartPageIndex(para) == pageIndex) {
                    builder.moveToParagraph(paragraphs.indexOf(para), 0);
                    builder.startBookmark("BM_Page" + pageIndex);
                    builder.endBookmark("BM_Page" + pageIndex);
                    pageIndex++;
                }
            }
        }

        collector = new LayoutCollector(doc);
        LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);

        int PageRelativeY = 50;
        int PageRelativeX = 50;

        for (Bookmark bookmark : doc.getRange().getBookmarks()) {
            if (bookmark.getName().startsWith("BM_")) {
                Paragraph para = (Paragraph) bookmark.getBookmarkStart().getParentNode();

                Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);


                watermark.setTop(PageRelativeY);
                watermark.setLeft(PageRelativeX);

                watermark.getImageData().setImage(watermarkImagePath);
                //Set the width height according to your requirements
                watermark.setWidth(400);
                watermark.setHeight(600);
                watermark.setBehindText(true);

                para.appendChild(watermark);

                watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
                watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);

                Boolean isInCell = bookmark.getBookmarkStart().getAncestor(NodeType.CELL) != null;
                if (isInCell) {
                    Object renderObject = collector.getEntity(bookmark.getBookmarkStart());
                    layoutEnumerator.setCurrent(renderObject);

                    layoutEnumerator.moveParent(LayoutEntityType.CELL);

                    watermark.setTop(PageRelativeY - layoutEnumerator.getRectangle().getY());
                    watermark.setLeft(PageRelativeX - layoutEnumerator.getRectangle().getX());
                }
            }
        }
    }

    public static void fitTableToPageWidth(Table table) {
        Section section = (Section) table.getAncestor(NodeType.SECTION);
        double tableWidth = 0;
        for (Row row : table.getRows()) {
            double rowWidth = 0;

            for (Cell cell : row.getCells()) {
                rowWidth += cell.getCellFormat().getWidth();
                cell.getCellFormat().setFitText(true);
            }
            if (rowWidth > tableWidth)
            {
                tableWidth = rowWidth;
            }
        }
        double pageWidth = section.getPageSetup().getPageWidth() - (section.getPageSetup().getLeftMargin() + section.getPageSetup().getRightMargin());
        for(Row row : table.getRows()) {
            for(Cell cell : row.getCells())
            {
                double cellRatio = cell.getCellFormat().getWidth() / tableWidth;
                cell.getCellFormat().setWidth(cellRatio * pageWidth);
            }
        }
    }
}
